package com.luoyx.vjsb.authority.security;

import com.luoyx.vjsb.authority.util.UserUtil;
import com.luoyx.vjsb.core.entity.SysUser;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * <p>
 * 添加用户权限和判断用户是否可以登录
 * </p>
 *
 * @author luoyuanxiang
 * @date 2020/5/4 17:15
 */
@Data
public class SecurityUserDetails implements UserDetails {

    private SysUser user;

    public SecurityUserDetails(SysUser user) {
        if (user != null) {
            this.user = user;
        }
    }

    /**
     * 添加用户拥有的权限和角色
     *
     * @return 1
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<String> roles = UserUtil.getRoles(user);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        // 添加角色
        if (roles != null && roles.size() > 0) {
            // lambda表达式
            roles.forEach(item -> authorityList.add(new SimpleGrantedAuthority("ROLE_" + item)));
        }

        Set<String> permissions = UserUtil.getPermissions(user);
        // 添加请求权限
        if (permissions != null && permissions.size() > 0) {
            permissions.forEach(s -> authorityList.add(new SimpleGrantedAuthority(s)));
        }
        return authorityList;
    }

    /**
     * Returns the password used to authenticate the user.
     *
     * @return the password
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * Returns the username used to authenticate the user. Cannot return <code>null</code>.
     *
     * @return the username (never <code>null</code>)
     */
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    /**
     * 账户是否过期
     *
     * @return 1
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 是否禁用
     *
     * @return 1
     */
    @Override
    public boolean isAccountNonLocked() {
        return user.getAvailable();
    }

    /**
     * 密码是否过期
     *
     * @return 1
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否启用
     *
     * @return 1
     */
    @Override
    public boolean isEnabled() {
        return user.getAvailable();
    }
}
